<?php
namespace app\common\logic;

use think\Model;
use app\common\model\StateChange as StateChangeModel;
use app\common\model\SystemSet as SystemSetModel;
use app\common\model\HuiYuanSupervise;

class StateChange extends Model
{
	protected $state;
	protected $system;
	protected function initialize()
	{
		parent::initialize();
		$this->state = new StateChangeModel;
		$this->system = new SystemSetModel;
		$this->member_model= new HuiYuanSupervise();
	}
	/**
	 * 订单充值查阅与审核
	 */

	public function throughAudit()
	{
		return $this->state->throughAudit();
	}
	/**
	 * 查询未审核线下充值订单
	 * @param unknown $limit
	 * @return unknown
	 */
	public function czListNo($limit){
		$where = 'zt<1 and ydzt<1 and czclass=2';
		$order = 'id desc';
		$query = $this->state->PaniageLists($where,$limit,$order);
		return $query;
	}
	/**
	 * 查询已审核线下充值订单
	 * @return multitype:
	 */
	public function czListWhere(){
		return array_filter(input('post.'));
	}
	public function czListOK(){
		StateChange::startTrans();
		try{
			$where['a.nbzh']=['<',1];$where['a.czclass']=['between','1,2'];$where['a.czadmin']=['<>',''];
			
			if(input('us_sql')){
				$where['a.username']=input('us_sql');
			}
			$query = $this->state->CzListZhenSongBaiFeng($where,10000);
	
			$where_sql = $this->czListWhere();
			$where_a=array();
			$star='';$end='';
			foreach ($where_sql as $k => $v)
			{
				if($k !='sDate1' || $k != 'sDate2'){
					if($k == 'us_sql'){
						$where['a.username']=$where_sql[$k];
					}elseif($k == 'ddzt'){
						$where['zt']=$where_sql[$k];
					}else{
						$where[$k]=$where_sql[$k];
					}
				}else{
					$star=strtotime($where_sql['sDate1']." 00:00:00");
					$end=strtotime($where_sql['sDate2']." 23:59:59");
					$where['a.cztime']=['between',$star.','.$end];
				}
			}
			$query = $this->state->CzListZhenSongBaiFeng($where,16);
			StateChange::commit();
		}catch (\Exception $e){
			StateChange::rollback();
		}
		return $query;
	}
	
	public function oneKeyDelFail($stua){
		$where="zt<0";
		$query = $this->state->delSelectChongZhi($where);
		foreach($query as $v){
			$id = $v['id'];
			$sure=$this->state->chongZhiDel($id);
		}
		$this->system->alertWin('更新成功', "/admin/recharge/cz_list_no?stua=".$stua);
		$this->member_model->caozuorizhi_xieru("一键清空充值审核未通过的记录");
	}

	/**
	 * 出款成功
	 */
	public function successTurnover(){
		StateChange::startTrans();
		$data=array('zt'=>1);
		$where=array('id'=>input('param.czid'),'czadmin'=>$_COOKIE['user'],'ifck'=>1,'zt'=>['<',1]);
		
		try{
			$query = $this->system->dFind('tixian_list',$where);
			$d = StateChange::name('username')->where('username',$query['username'])->find();
			if($query['id']){
				$data_tx=array('txzje'=>$d['txzje']+$query['txje']);
				StateChange::name('username')->where('username',$query['username'])->update($data_tx);
				StateChange::name('tixian_list')->where('id',$query['id'])->update($data);
			}
			StateChange::commit();
		}catch (\Exception $e){
			StateChange::rollback();
			return $this->system->alertWin('操作错误，已有管理员在处理或者还未进行审核！', "/admin/recharge/tx_list");
		}
		return $this->system->alertWin('操作成功', "/admin/recharge/tx_list");
	}
	/**
	 * 返回提现
	 */
	public function tiXianReturnBeiZhu(){
		StateChange::startTrans();
		$czid=input('param.czid');
		$where=array('id'=>$czid);
		try{
			$query = $this->system->dFind('tixian_list',$where);
			$q = StateChange::name('username')->where('username',$query['username'])->find();
			if($query['id']){
				$data['username']=$query['username'];
				$data['txje']=$query['txje'];
				$data['zt']=2;
				$data['ifck']=$query['ifck'];
				$data['txtime']=$query['txtime'];
				$data['txip']=$query['txip'];
				$data['txhje'] = $query['txhje'];
				$data['thqje'] = $q['je'];
				$data['czadmin']=$_COOKIE['user'];
				$data['beizhu']=input('param.tuibz')?input('param.tuibz'):'无';
				$data['shtime']=time();
				StateChange::name('tixian_list_no')->insert($data);
				StateChange::name('tixian_list')->where($where)->delete();
				$d = array('je'=>$q['je']+$query['txje']);
				StateChange::name('username')->where('username',$query['username'])->update($d);
				$this->state->UserFaSong($query['username'], "您提现：".$query['txje']." 被驳回，原因：".input('param.tuibz'));
			}
			StateChange::commit();
		}catch (\Exception $e){
			StateChange::rollback();
		}
		return $this->system->alertWin('操作成功！',"/admin/recharge/tx_list");
	}
	
	public function txListOk($limit,$username,$time1,$time2){
		
		$a=$username;
		
		if($time1 && $time2){
		    $star = $time1;
		    $end = $time2;
		    $where['tixian.txtime']=['between',strtotime($star).','.strtotime($end)];
		}
		
		
		if(input('get.us_sql')){
			$where['tixian.zt']=['>',0];
			$where['tixian.czadmin']=['<>',''];
			$where['tixian.nbzh']=0;
			
		}else{
			$where['tixian.zt']=['>',0];
			$where['tixian.czadmin']=['<>',''];
			$where['tixian.nbzh']=0;
		}
		$field=['tixian.id as uuid','tixian.shtime as shtime','tixian.zt as zt','tixian.nbzh as nbzh','tixian.txje as txje','tixian.ifck as ifck','tixian.txtime as txtime','tixian.txip as txip','tixian.czadmin as czadmin','tixian.shadmin as shadmin'];

		
		return StateChange::name('tixian_list')->alias('tixian')
					->field($field)
					->join('__USERNAME__ member','member.username = tixian.username')
					->field(['member.username as username','member.bankren as bankren','member.bankname as bankname','member.bankno as bankno'])
					->join('__US_CLASS__ usclass','usclass.id = member.us_class')
					->field(['usclass.class_name as class_name'])
					->where($where)->where('tixian.username','like','%'.$a.'%')->order('tixian.id desc')
					->paginate($limit,false,array('query'=>array('sDate1'=>$time1,'sDate2'=>$time2)));
	}
	public function txListNo($limit,$username,$time1,$time2){
		$a=$username;
		
		if($time1 && $time2){
		    $star = $time1;
		    $end = $time2;
		    $where['tixian.txtime']=['between',strtotime($star).','.strtotime($end)];
		}
		$where['tixian.zt']=['>',1];
		$where['tixian.beizhu']=['<>',''];
		$field=['tixian.id as uuid','tixian.shtime as shtime','tixian.zt as zt','tixian.beizhu as beizhu','tixian.txje as txje','tixian.ifck as ifck','tixian.txtime as txtime','tixian.txip as txip','tixian.czadmin as czadmin'];
		return StateChange::name('tixian_list_no')->alias('tixian')
					->field($field)
					->join('__USERNAME__ member','member.username = tixian.username')
					->field(['member.username as username','member.bankren as bankren','member.bankname as bankname','member.bankno as bankno'])
					->join('__US_CLASS__ usclass','usclass.id = member.us_class')
					->field(['usclass.class_name as class_name'])
					->where($where)->where('tixian.username','like','%'.$a.'%')->order('tixian.id desc')
					->paginate($limit,false,array('query'=>array('sDate1'=>$time1,'sDate2'=>$time2)));
	}
	/**
	 * 彩金列表
	 */	
	public function caiJinList($limit,$username,$time1,$time2){
		$a=$username;
		
		if($time1 && $time2){
		    $star = $time1;
		    $end = $time2;
		    $where['cj.fstime']=['between',strtotime($star).','.strtotime($end)];
		}
		
		$where['username']=['<>',''];
		$field=['cj.id as uid','cj.username as username','cj.cjje as cjje','cj.fstime as fstime','cj.beizhu as beizhu','cj.czadmin as czadmin'];
		return StateChange::name('caijin_list')->alias('cj')
					->field($field)
					->join('__US_CLASS__ uc','uc.id = cj.user_class')
					->field(['uc.class_name as class_name'])
					->where($where)
					->where('cj.username','like','%'.$a.'%')
					->order('cj.id desc')
		            ->paginate($limit,false,array('query'=>array('sDate1'=>$time1,'sDate2'=>$time2)));
	}
	/**
	 * 手工扣款列表
	 * @param unknown $limit
	 */
	public function czSgkkList($limit,$username,$time1,$time2){
		$a=$username;				
		if($time1 && $time2){
		    $star = $time1;
		    $end = $time2;
		    $where['kktime']=['between',strtotime($star).','.strtotime($end)];
		}
			$where['username']=['<>',''];
		
		$order='id desc';
		return StateChange::name('sgkk_list')->where($where)->where('username','like','%'.$a.'%')->order($order)->paginate($limit);
	}
	
	public function czSgczList($limit,$username,$time1,$time2){
		$a=$username;				
		if($time1 && $time2){
		    $star = $time1;
		    $end = $time2;
		    $where['cztime']=['between',strtotime($star).','.strtotime($end)];
		}
			$where['czadmin']=['<>',''];
			$where['nbzh']=['<',1];
			$where['czclass']=3;
		
		$order='id desc';
		
		return StateChange::name('chongzhi_list')->where($where)->where('username','like','%'.$a.'%')->order($order)->paginate($limit);
	}
	/**
	 * 手工充值
	 */
	public function ManualRecharge(){
		if(input('post.')){
			$input = array_filter(input('post.'));
			$cztime = time();
			$ddbh = 'S_'.$cztime.rand(1,99);
			$xxbank = '手工充值';
			$openren = '手工充值';
			$czip = $this->system->GetIP();
			$bankekh = '手工充值';
			$data = array('username'=>$input['cgcz_user'],'je'=>$input['cgcz_je'],'beizhu'=>$input['cgcz_bzxx'],
							'cztime'=>$cztime,'ddbh'=>$ddbh,'xxbank'=>$xxbank,'zt'=>1,'ydzt'=>1,'czclass'=>3,'czadmin'=>$_COOKIE['user'],'openren'=>$openren,'czip'=>$czip,
							'bankekh'=>$bankekh,'method'=>intval(input('post.method')));
			$where = array('username'=>$input['cgcz_user']);
			$query = $this->system->dFind('username',$where);
			if($input['cgcz_je']>0){
				if($query['id']){
					$savedata = array('je'=>$query['je']+$input['cgcz_je'],'dml'=>$query['dml']+$input['cgcz_dml']);
					if( 0==intval(input('post.method')) ) {$savedata['czzje'] = $query['czzje']+$input['cgcz_je'];}
					$data['czhje'] = $savedata['je']; //充值后金额
					$this->state->InsertRecharge('chongzhi_list', $data);
					$this->state->SaveRecharge('username', $where, $savedata);
					StateChange::name('username')->where('username',$input['cgcz_user'])->setInc('cz_num');
					$this->state->UserFaSong($input['cgcz_user'], "您账户金额增加：".$input['cgcz_je']."，原因：".$input['cgcz_bzxx']);
					$this->member_model->caozuorizhi_xieru("给".$input['cgcz_user']."账户加款".$input['cgcz_je']);
					return $this->system->alertWin('操作成功', '/admin/Recharge/cz_sgcz');
				}else 
					alert_back('该用户不存在');
			}else 
				alert_back('充值金额必须大于0');
				
		}
	}
	/**
	 * 手工扣款
	 */
	public function ManualDeduction()
	{
		if(input('post.')){
			$t = input('post.');
			$kktime = time();
			$data = array('username'=>$t['cgcz_user'],'kkje'=>$t['cgcz_je'],'kkliyou'=>$t['cgcz_bzxx'],'czadmin'=>$_COOKIE['user'],'kktime'=>$kktime,'method'=>$t['method']);
			$where = array('username'=>$t['cgcz_user']);
			$query = $this->system->dFind('username',$where);
			if($t['cgcz_je']>0){
				if($query['id']){
					if($query['je']>$t['cgcz_je']){
						$dml = $query['dml']-$t['cgcz_dml'];
						if($dml<0){$dml=0;}
						$savedata = array('je'=>round(($query['je']-$t['cgcz_je']),2),'dml'=>$dml);
						if( 1==intval($t['method']) ) $savedata['txzje']=round(($query['txzje']-$t['cgcz_je']),2);
						/**@todo*/
						$data['kkhje'] = round(($query['je']-$t['cgcz_je']),2);

						$this->state->InsertRecharge('sgkk_list', $data);
						$this->state->SaveRecharge('username', $where, $savedata);
						$this->state->UserFaSong($t['cgcz_user'], "您账户金额减少：".$t['cgcz_je']."，原因：".$t['cgcz_bzxx']);
						$this->member_model->caozuorizhi_xieru("给".$t['cgcz_user']."账户扣款".$t['cgcz_je']);
						return $this->system->alertWin('操作成功！', '/admin/Recharge/cz_sgkk?id='.input('param.id').'&cid='.input('param.cid'));
					}else{
						alert_back('用户余额不足！');
					}
				}else{
					alert_back('该用户不存在！');
				}
			}else{
				alert_back('扣款金额不能为负！');
			}
		}
	}
	/**
	 * 彩金发放
	 */
	public function PaymentOfPrizeMoney()
	{
		if(input('post.')){
			$t = input('post.');
			$user = explode("\n", $t['cgcz_user']);
			
			foreach ($user as $v){
			    $kktime = time();
			    $v = preg_replace('/\r|\n/', '', $v);
			    $where = array('username'=>$v);
			    $query = $this->system->dFind('username',$where);
			    $data = array('username'=>$v,'cjje'=>$t['cgcz_je'],'beizhu'=>$t['cgcz_bzxx'],'czadmin'=>$_COOKIE['user'],'fstime'=>$kktime,'user_class'=>$query['us_class']);
			    
			    if($t['cgcz_je'] > 0){
			        if($query['id']){
		                $savedata = array('je'=>$query['je']+$t['cgcz_je'],'dml'=>$query['dml']+$t['cgcz_dml'],'zcjje'=>$query['zcjje']+$t['cgcz_je']);
		                $data['cjhje'] = $savedata['je']; //彩金发放后金额
		                $this->state->InsertRecharge('caijin_list', $data);
		                $this->state->SaveRecharge('username', $where, $savedata);
		                $this->state->UserFaSong($v, "系统彩金发放，金额：".$t['cgcz_je']."，原因：".$t['cgcz_bzxx']);
		                $this->member_model->caozuorizhi_xieru('给账户:'.$v."发放彩金".$t['cgcz_je']);
			        }else{
			            alert_back('（'.$v.'）该用户不存在！');
			        }
			    }else{
			        alert_back('扣款金额不能为负！');
			    }
			}
			js_tishi('操作成功！', '/admin/Recharge/cj_list');
		}
	}
	/**
	 * 内部充值
	 */
	public function InternalRecharge()
	{
		if(input('post.')){
			$input = array_filter(input('post.'));
			$cztime = time();
			$ddbh = 'S_'.$cztime.rand(1,99);
			$xxbank = '/无/';
			$openren = '/无/';
			$czip = $this->system->GetIP();
			$bankekh = '/无/-/无/';
			$check = $this->system->dFind('username',array('username'=>$input['cgcz_user']));
			
			if($check['nbzh'] == 0){
			    alert_back('该用户不是内部账户');
			}
			$data = array('username'=>$input['cgcz_user'],'je'=>$input['cgcz_je'],'beizhu'=>$input['cgcz_dml'],
					'cztime'=>$cztime,'ddbh'=>$ddbh,'xxbank'=>$xxbank,'zt'=>1,'ydzt'=>1,'czclass'=>4,'czadmin'=>$_COOKIE['user'],'openren'=>$openren,'czip'=>$czip,
					'bankekh'=>$bankekh,'nbzh'=>1);
			$where = array('username'=>$input['cgcz_user']);
			$query = $this->system->dFind('username',$where);
			if($input['cgcz_je']>0){
				if($query['id']){
					$savedata = array('je'=>$query['je']+$input['cgcz_je']);
					$this->state->InsertRecharge('chongzhi_list', $data);
					$this->state->SaveRecharge('username', $where, $savedata);
					$this->member_model->caozuorizhi_xieru('给内部账户:'.$query['username']."充值".$input['cgcz_je']);
					return $this->system->alertWin('操作成功', '/admin/Recharge/cz_nbcz_list');

				}else
					alert_back('该用户不存在');
			}else
				alert_back('充值金额必须大于0');
		
		}
	}
	
	public function InternalList($limit,$username,$time1,$time2){
		$a=$username;				
		if($time1 && $time2){
		    $star = $time1;
		    $end = $time2;
		    $where['cztime']=['between',strtotime($star).','.strtotime($end)];
		}
		$where['nbzh']=1;
		$order= 'id desc';
		return StateChange::name('chongzhi_list')->where('username','like','%'.$a.'%')->where($where)->order($order)->paginate($limit);
	}
	
	public function TiXianNeiBuList($limit)
	{
		$a='';
		if(input('post.')){
			$wherea = array_filter(input('post.'));
			$where = array();
			foreach ($wherea as $k=>$v){
				if($k == 'us_sql'){
					$a=$wherea[$k];
				}
				if($k == 'sDate1' || $k == 'sDate2'){
					if($wherea['sDate1'] != '' && $wherea['sDate2'] !=''){
						$star = strtotime($wherea['sDate1']." 00:00:00");
						$end = strtotime($wherea['sDate2']." 23:59:59");
						$where['kktime']=['between',$star.','.$end];
					}
				}
			}
		}
		$where['nbzh']=1;
		$order= 'id desc';
		return StateChange::name('tixian_list')->where($where)->where('username','like','%'.$a.'%')->order($order)->paginate($limit);
	}
}